import uuid

from flask import Flask, request
from flask.json import jsonify

import config as cfg
from utils.work_db import close_session, rollback_session
from utils.work_log import get_logger
from utils.work_web import register_blueprints

app = Flask(__name__)

app.config.from_object(cfg)
app.secret_key = cfg.SECRET_KET
register_blueprints(app)

log = get_logger(__name__)


@app.before_request
def before_request():
    log.info('========= 请求' + str(request.url))


@app.errorhandler(500)
def err500(e):
    rollback_session()
    trace_id = str(uuid.uuid1())
    log.error('trace_id: %s\n%s' % (trace_id, str(e)))
    return jsonify({'code': -1, 'msg': '调用异常！', 'trace_id': trace_id})


@app.errorhandler(404)
def err404(e):
    trace_id = str(uuid.uuid1())
    log.error('trace_id: %s\n%s' % (trace_id, str(e)))
    return jsonify({'code': -1, 'msg': 'not found！', 'trace_id': trace_id})


@app.after_request
def after_request(res):
    close_session()  # 关闭数据库会话
    return res


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=8089, threaded=False)
